package com.ctshk.rpc.season.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SeasonType;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.goods.CommoditySeasonDTO;
import com.ctshk.rpc.goods.service.ICommodityService;
import com.ctshk.rpc.season.dto.PackageProductCostDTO;
import com.ctshk.rpc.season.dto.SeasonFixedProductPackageCommodityDTO;
import com.ctshk.rpc.season.entity.SeasonFixedProductPackageCommodity;
import com.ctshk.rpc.season.mapper.SeasonFixedProductPackageCommodityMapper;
import com.ctshk.rpc.season.req.PassengerReq;
import com.ctshk.rpc.season.req.SeasonFixedProductPackageCommodityReq;
import com.ctshk.rpc.season.req.UpdatePackageProductReq;
import com.ctshk.rpc.season.service.ISeasonFixedProductPackageCommodityService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套票-固定套票单项产品打包-商品表 服务实现类
 * </p>
 *
 * @author 杨林
 * @since 2021-03-09
 */
@DubboService
public class SeasonFixedProductPackageCommodityServiceImpl extends ServiceImpl<SeasonFixedProductPackageCommodityMapper, SeasonFixedProductPackageCommodity> implements ISeasonFixedProductPackageCommodityService {

    @Autowired
    private SeasonFixedProductPackageCommodityMapper seasonFixedProductPackageCommodityMapper;

    @DubboReference
    private ICommodityService commodityService;

    @Override
    public PackageProductCostDTO getCommodityProductPrice(Long productId, LocalDate departureDate, Long userId, Integer channelType, Long attrId1, Long attrId2) {
        PackageProductCostDTO costDTO = new PackageProductCostDTO();
        ;
        try {
            Result<CommoditySeasonDTO> result = commodityService.findCommodityPriceById(productId, departureDate, attrId1, attrId2);
            if (null != result && null != result.getData() && result.getData().getSort() > 0) {
                costDTO.setCostPrice(result.getData().getPrice());
                costDTO.setStock(result.getData().getSort());
            }
        } catch (Exception e) {
            log.error("调用商品服务获取价格发生异常", e);
        }
        return costDTO;
    }

    /* @MethodName: 获取 固定套票默认商品的价格
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/20 11:50
     **/
    @Override
    public BigDecimal getDefaultCommodityPrice(Long packageId, LocalDate queryDate, Long userId, Integer channelType) {
        BigDecimal bd = BigDecimal.ZERO;
        //获取默认的 商品产品
        SeasonFixedProductPackageCommodity commodity = seasonFixedProductPackageCommodityMapper.selectOne(
                new QueryWrapper<SeasonFixedProductPackageCommodity>().lambda().
                        eq(SeasonFixedProductPackageCommodity::getIsDefault, SeasonType.YES_DEFAULT.getCode()).
                        eq(SeasonFixedProductPackageCommodity::getIsDeleted, IsDeletedCode.NO.getCode()).
                        eq(SeasonFixedProductPackageCommodity::getPackageId, packageId)
        );
        if (null != commodity) {
            bd = getCommodityProductPrice(commodity.getProductId(), queryDate, userId, channelType, null, null).getCostPrice();
        }
        return bd;
    }

    @Override
    public List<SeasonFixedProductPackageCommodityDTO> getCommodityByPackageId(Long packageId, LocalDate queryDate, Long userId, Integer channelType) {
        List<SeasonFixedProductPackageCommodity> resultList = seasonFixedProductPackageCommodityMapper.selectList(
                new QueryWrapper<SeasonFixedProductPackageCommodity>().lambda().
                        eq(SeasonFixedProductPackageCommodity::getIsDeleted, IsDeletedCode.NO.getCode()).
                        eq(SeasonFixedProductPackageCommodity::getPackageId, packageId)
        );
        List<SeasonFixedProductPackageCommodityDTO> resultDtoList = new ArrayList<>();
        if (null != resultList && resultList.size() > 0) {
            for (SeasonFixedProductPackageCommodity result : resultList) {
                SeasonFixedProductPackageCommodityDTO resultDto = EntityUtil.copy(result, SeasonFixedProductPackageCommodityDTO.class);
                resultDto.setCost(getCommodityProductPrice(resultDto.getProductId(), queryDate, userId, channelType, null, null).getCostPrice());
                resultDtoList.add(resultDto);
            }
        }
        return resultDtoList;
    }

    @Override
    public List<SeasonFixedProductPackageCommodityDTO> getDefaultCommodityData(Long packageId, LocalDate queryDate, Long userId, Integer channelType) {
        List<SeasonFixedProductPackageCommodity> resultList = seasonFixedProductPackageCommodityMapper.selectList(
                new QueryWrapper<SeasonFixedProductPackageCommodity>().lambda().
                        eq(SeasonFixedProductPackageCommodity::getIsDefault, SeasonType.YES_DEFAULT.getCode()).
                        eq(SeasonFixedProductPackageCommodity::getIsDeleted, IsDeletedCode.NO.getCode()).
                        eq(SeasonFixedProductPackageCommodity::getPackageId, packageId)
        );
        List<SeasonFixedProductPackageCommodityDTO> resultDtoList = new ArrayList<>();
        if (null != resultList && resultList.size() > 0) {
            for (SeasonFixedProductPackageCommodity result : resultList) {
                SeasonFixedProductPackageCommodityDTO resultDto = EntityUtil.copy(result, SeasonFixedProductPackageCommodityDTO.class);
                resultDto.setCost(getCommodityProductPrice(resultDto.getProductId(), queryDate, userId, channelType, null, null).getCostPrice());
                resultDtoList.add(resultDto);
            }
        }
        return resultDtoList;
    }

    /* @MethodName: 批量保存 商品产品信息
     * @Description: TODO
     * @Param: userId 用户id  productId 产品id packageId 打包id  scenicReqList 商品集合
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/9 18:27
     **/
    @Override
    public void batchCommodityProduct(Long userId, Long packageId, List<SeasonFixedProductPackageCommodityReq> CommodityList) {
        LocalDateTime now = LocalDateTime.now();
        List<SeasonFixedProductPackageCommodity> lfList = CommodityList.stream().map(
                CommodityReq -> {
                    SeasonFixedProductPackageCommodity scenic = EntityUtil.copy(CommodityReq, SeasonFixedProductPackageCommodity.class);
                    scenic.setCreateId(userId);
                    scenic.setPackageId(packageId);
                    scenic.setGmtCreate(now);
                    scenic.setId(IdWorker.getId());
                    scenic.setIsDeleted(IsDeletedCode.NO.getCode());
                    return scenic;
                }
        ).collect(Collectors.toList());
        seasonFixedProductPackageCommodityMapper.insertBatchSomeColumn(lfList);
    }

    /* @MethodName: 获取固定套票 商品信息
     * @Description: TODO
     * @Param: fixedSeasonId 固定套票id   packageId 产品打包id
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/11 13:40
     **/
    @Override
    public List<SeasonFixedProductPackageCommodityDTO> getSeasonFixedProductCommodityDtoList(Long packageId) {
        List<SeasonFixedProductPackageCommodity> productPackageCommodityList = getSeasonFixedProductCommodityList(packageId);
        List<SeasonFixedProductPackageCommodityDTO> list = new LinkedList<>();
        if (null != productPackageCommodityList && productPackageCommodityList.size() > 0) {
            list = productPackageCommodityList.stream().map(
                    Commodity -> {
                        SeasonFixedProductPackageCommodityDTO ScenicDto = EntityUtil.copy(Commodity, SeasonFixedProductPackageCommodityDTO.class);
                        return ScenicDto;
                    }
            ).collect(Collectors.toList());
        }
        return list;
    }

    /* @MethodName: 删除原来的景点票产品
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/12 16:26
     **/
    @Override
    public void deletePreviousCommodity(Long userId, Long packageId) {
        LocalDateTime now = LocalDateTime.now();
        UpdateWrapper<SeasonFixedProductPackageCommodity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("modified_id", userId);//修改人
        updateWrapper.set("is_deleted", IsDeletedCode.YES.getCode());//删除
        updateWrapper.set("gmt_modified", now);//修改时间
        updateWrapper.eq("package_id", packageId);
        seasonFixedProductPackageCommodityMapper.update(null, updateWrapper);
    }


    /* @MethodName: 获取商品的成本差价
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/23 13:49
     **/
    @Override
    public List<SeasonFixedProductPackageCommodityDTO> getCommodityDifferencePrice(UpdatePackageProductReq req) {
        Long packageId = req.getPackageId();
        //多少人
        Integer num = req.getPassengerReqList().stream().mapToInt(passenger -> passenger.getPassengerNum()).sum();
        BigDecimal num1 = new BigDecimal(String.valueOf(num));
        LocalDate queryDate = req.getStartDate();
        List<SeasonFixedProductPackageCommodityDTO> list = new LinkedList<>();
        SeasonFixedProductPackageCommodityDTO defaultDto = getSeasonFixedDefaultProductCommodity(packageId, queryDate, req.getPassengerReqList(), req.getUserId());
        list.add(defaultDto);
        BigDecimal flagCost = defaultDto.getCost();
        List<SeasonFixedProductPackageCommodity> CommodityList = getCommodity(packageId, SeasonType.NO_DEFAULT.getCode());
        CommodityList.stream().forEach(
                Commodity -> {
                    Long CommodityProductId = Commodity.getProductId();
                    SeasonFixedProductPackageCommodityDTO CommodityDto = EntityUtil.copy(Commodity, SeasonFixedProductPackageCommodityDTO.class);
                    BigDecimal singleCost = BigDecimal.ZERO;
                    BigDecimal scenicCost = singleCost.multiply(num1);
                    CommodityDto.setCost(scenicCost);
                    if (scenicCost.compareTo(BigDecimal.ZERO) == 0) {//表示没有库存
                        CommodityDto.setPriceDifference("售罄");
                    } else {
                        CommodityDto.setPriceDifference(String.valueOf(flagCost.subtract(scenicCost)));//减法
                    }
                    CommodityDto.setSingleCost(singleCost);//单间单晚成本
                    list.add(CommodityDto);
                });


        return list;
    }

    public SeasonFixedProductPackageCommodityDTO getSeasonFixedDefaultProductCommodity(Long packageId, LocalDate queryDate, List<PassengerReq> passengerReqList, Long userId) {
        SeasonFixedProductPackageCommodity Commodity = getCommodity(packageId, SeasonType.YES_DEFAULT.getCode()).get(0);
        SeasonFixedProductPackageCommodityDTO CommodityDTO = EntityUtil.copy(Commodity, SeasonFixedProductPackageCommodityDTO.class);
        BigDecimal CommodityCost = BigDecimal.ZERO;

        //旅客类型集合
        Integer num = passengerReqList.stream().mapToInt(passenger -> passenger.getPassengerNum()).sum();
        BigDecimal num1 = new BigDecimal(String.valueOf(num));
        BigDecimal totalCost = CommodityCost.multiply(num1);
        CommodityDTO.setCost(totalCost);
        if (CommodityCost.compareTo(BigDecimal.ZERO) == 0) {
            CommodityDTO.setPriceDifference("售罄");
        } else {
            CommodityDTO.setPriceDifference("0");
        }
        return CommodityDTO;
    }


    /* @MethodName: 获取固定套票 商品信息
     * @Description: TODO
     * @Param: fixedSeasonId 固定套票id   packageId 产品打包id
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/11 13:40
     **/
    private List<SeasonFixedProductPackageCommodity> getSeasonFixedProductCommodityList(Long packageId) {
        QueryWrapper<SeasonFixedProductPackageCommodity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("package_id", packageId);
        queryWrapper.eq("is_deleted", IsDeletedCode.NO.getCode());
        return seasonFixedProductPackageCommodityMapper.selectList(queryWrapper);
    }


    /* @MethodName: 获取商品信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/2 11:19
     **/
    private List<SeasonFixedProductPackageCommodity> getCommodity(Long packageId, Integer isDefault) {
        return seasonFixedProductPackageCommodityMapper.selectList(
                new QueryWrapper<SeasonFixedProductPackageCommodity>().lambda()
                        .eq(SeasonFixedProductPackageCommodity::getIsDefault, IsDeletedCode.NO.getCode())
                        .eq(SeasonFixedProductPackageCommodity::getPackageId, packageId)
                        .eq(SeasonFixedProductPackageCommodity::getIsDefault, isDefault)
        );

    }
}
